package com.ks.test.app;

import java.lang.instrument.ClassDefinition;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class Demo5 {

    public static void main(String[] args) throws Exception {

        ClassPool classPool = ClassPool.getDefault();

        CtClass ctClass = classPool.get("com.ks.test.app.Point");

        ctClass.stopPruning(true);
        // javaassist freezes methods if their bytecode is saved
        // defrost so we can still make changes.
        if (ctClass.isFrozen()) {
            ctClass.defrost();
        }

        CtMethod ctMethod = ctClass.getDeclaredMethod("move");
        ctMethod.insertBefore("{ System.out.println(\"Wheeeeee!\"); }");
        byte[] bytecode = ctClass.toBytecode();

        ClassDefinition definition = new ClassDefinition(Class.forName("com.ks.test.app.Point"), bytecode);
        RedefineClassAgent.redefineClasses(definition);

        Point point = new Point(1, 1);
        point.move(1, 2);
    }
}
